package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/emps")
public class EmpController {
    @Autowired
    private EmpService empService;
    @Autowired
    private DeptService deptService;

    @GetMapping
    public Result page(EmpQueryParam param) {
        log.info("员工列表查询条件：{}", param);
        // 调用Service层查询分页数据
        Page<Emp> page = new Page<>(param.getPage(), param.getPageSize());
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(param.getName() != null && !param.getName().isEmpty(), Emp::getName, param.getName())
                .eq(param.getGender() != null, Emp::getGender, param.getGender())
                .between(param.getBegin() != null && param.getEnd() != null, Emp::getEntryDate, param.getBegin(), param.getEnd());

        //添加排序规则
        page.addOrder(OrderItem.desc("update_time"));
        //得到分页结果
        page = empService.page(page, queryWrapper);
        List<Emp> emps = page.getRecords();
        if (emps != null && !emps.isEmpty()) {
            Set<Integer> deptIds = emps.stream().filter(emp -> emp.getId() != null).map(Emp::getDeptId).collect(Collectors.toSet());
            log.info("depts{}", deptIds);
            List<Dept> depts = deptService.listByIds(deptIds);
            Map<Integer, String> collect = depts.stream().collect(Collectors.toMap(Dept::getId, Dept::getName));
            for (Emp emp : emps) {
                emp.setDeptName(collect.get(emp.getDeptId()));
            }
        }
        // 返回结果
        return Result.success(new PageResult<>(page.getTotal(), page.getRecords()));
    }

    @PostMapping
    public Result save(@RequestBody Emp emp) {
        log.info("新增员工，员工信息：{}", emp);
        // 调用service层方法保存员工信息和员工的工作经历信息
        boolean r=empService.saveEmp(emp);
        return r? Result.success(): Result.error("员工新增失败");
    }

    @DeleteMapping
    public Result delete(@RequestParam List<Integer> ids) {
        log.info("批量删除员工，{}", ids);

        // 调用service层方法批量删除员工信息和员工工作经历信息
        boolean r=empService.removeEmpsByIds(ids);

        return r? Result.success(): Result.error("员工删除失败");
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        log.info("根据ID查询员工信息，id：{}", id);
        Emp emp=  empService.getEmpById(id);
        return emp!=null? Result.success(emp): Result.error("未查询到员工信息");
    }

    @PutMapping
    public Result update(@RequestBody Emp emp) {
        log.info("修改员工信息，员工信息：{}", emp);

        // 调用service层方法修改员工信息
        boolean r=empService.updateEmpById(emp);
        return Result.success();
    }

    @GetMapping("/list")
    public Result list() {
        log.info("查询员工列表");

        // 调用service层方法查询员工列表
        return Result.success( empService.list());
    }
}
